package cn.hesion.linkedlist;

public class LinkedListTest {
    Node head; // 记录
    Node last; // 记录最后一个节点
    int size; // 记录数据的个数

    public LinkedListTest() {
        head = new Node(0, null);
        size = 0;
    }

    public void headinsert(Node node) {

        if (node != null) {
            if (head.next == null) {
                head.next = node;
                ++size;
                return;
            }
            Node temp = head.next;
            head.next = node;
            node.next = temp;
            ++size;
        }
    }

    public void tailInsert(Node node) {
        if (node != null) {
            if (head.next == null) {
                head.next = node;
                last = node;
                ++size;
                return;
            }
            last.next = node;
            last = node;
            ++size;
        }
    }

    public void centerInsert(int index, Node node) throws Exception {
        if (node != null) {
            if (index < 0 || index > size) throw new IndexOutOfBoundsException("超出链表范围");
            if (head.next == null) {
                head.next = node;
                ++size;
                return;
            }
            // 获取要插入的前一个节点
            Node preNode = get(index - 1);
            // 记录下要插入的节点的后一个节点 待会方便链接
            Node nextNde = preNode.next;
            preNode.next = node;
            node.next = nextNde;
            ++size;
        }

    }

    public Node get(int index) throws Exception {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("超出链表访问范围");
        }
        Node temp = head;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        return temp;
    }

    public void printLink() {
        Node temp = head;
        while (temp.next != null) {
            temp = temp.next;
            System.out.print(temp.data + "----->");

        }
    }

    public static void main(String[] args) throws Exception {
        LinkedListTest linkedListTest = new LinkedListTest();
//        linkedListTest.headinsert(new Node(3, null));
//        linkedListTest.headinsert(new Node(4, null));
//        linkedListTest.headinsert(new Node(5, null));
//        linkedListTest.tailInsert(new Node(5, null));
//        linkedListTest.tailInsert(new Node(6, null));
//        linkedListTest.tailInsert(new Node(7, null));
        linkedListTest.centerInsert(0,new Node(1,null));
        linkedListTest.centerInsert(1,new Node(2,null));
        linkedListTest.centerInsert(2,new Node(3,null));
        linkedListTest.centerInsert(2,new Node(3,null));
        linkedListTest.centerInsert(4,new Node(4,null));
        linkedListTest.printLink();

    }
}

class Node {
    int data;
    Node next;

    Node(int data, Node next) {
        this.data = data;
        this.next = next;
    }
}